//
//  FRQCroppedImageViewController.m
//  FRQBluetoothKit_Example
//
//  Created by admin on 2023/10/23.
//  Copyright © 2023 xuchunhai. All rights reserved.
//

#import "FRQCroppedImageViewController.h"
#import "CroppedImageViews.h"
#import "FRQDeviceImageViewController.h"
#import "FRQNoBluetoothYetViewController.h"
//#import <FRQBluetoothKit/FRQBluetoothManager.h>

@interface FRQCroppedImageViewController ()<FRQBluetoothManagerDelegate,FRQBImageOrVersionDelegte>
@property (nonatomic,strong) CroppedImageViews *croppedImageView;
@property (nonatomic,strong) CBPeripheral *MyPeripheral;
@end

@implementation FRQCroppedImageViewController

- (FRQNoBluetoothYetViewController *)extracted {
    FRQNoBluetoothYetViewController *view=[[FRQNoBluetoothYetViewController alloc] init];
    return view;
}

-(CroppedImageViews *)croppedImageView{
    if (nil==_croppedImageView) {
        _croppedImageView=skXibView(@"CroppedImageViews");
        [self.view addSubview:_croppedImageView];
        [_croppedImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.mas_topLayoutGuide);
            make.bottom.mas_equalTo(self.mas_bottomLayoutGuide);
            make.right.left.mas_equalTo(0);
        }];
        _croppedImageView.imageCrop.image=self.image;
        
        @weakify(self)
        [[_croppedImageView.btnShowOnDevice rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {

//            if(![[FRQBluetoothManager shareManager] isConnect]){
//                [SkToast SkToastShow:@"Bluetooth No Connect"];
//                return;
//            }
//            FRQDeviceImageViewController *view=[[FRQDeviceImageViewController alloc] init];
//            [self.navigationController pushViewController:view animated:YES];
//            return;
            
            @strongify(self)
            NSLog(@"%@,%@",skDevice.devName,self.MyPeripheral.name);
            if (!self.image) {
                return;
            }
            //蓝牙修改处   判断蓝牙是否存在
//            self.MyPeripheral = [[BlueManager shareInstance] getBluePeripheral];
            //[self.MyPeripheral.name isEqualToString:skDevice.devName]
            if([FRQBluetoothManager shareManager].isConnect == 1){//这里就可以传送图片数据了
                //正式需要更换
                [self appUserNftImageConversion];
                
            }else{

                FRQNoBluetoothYetViewController * view = [self extracted];

//                [self.navigationController pushViewController:view animated:YES];
                view.modalPresentationStyle=0;
                [self presentViewController:view animated:YES completion:^{
                    
                }];
            }
            
        }];
    }
    return _croppedImageView;
}
- (UIImage *)fixImageSizeWithImage:(UIImage *)image width:(CGFloat)width
{
    float actualHeight = width;
    float actualWidth = width;
    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [image drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    NSData *imageData = UIImagePNGRepresentation(img);
    UIGraphicsEndImageContext();
 
    return [UIImage imageWithData:imageData];
}
- (void)appUserNftImageConversion {
    SHOW_SVP(@"wait");
    UIImage *imageChange=[self fixImageSizeWithImage:self.image width:466];
    self.image=imageChange;
    //蓝牙12.01
    self.croppedImageView.btnShowOnDevice.enabled = NO;
    NSDictionary *dic=@{@"file":@"ImageUp"};
    [PKNetTools uploadImageURL:[NSString stringWithFormat:@"%@%@",skURL,@"app/user/nft/imageConversion"]
                    parameters:dic
                        images:@[self.image]
                          name:@"ImageUp"
                      fileName:@"ImageUp"
                      mimeType:@"ImageUp" progress:^(NSProgress * _Nonnull progress) {
        
    } callback:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        skNetModel *model=[skNetModel mj_objectWithKeyValues:responseObject];
        if(model.code==200){
            
            NSString *homeDir = NSHomeDirectory();
            NSString *binUrl=model.data;
            
            [PKNetTools downloadWithURL:binUrl fileDir:homeDir progress:^(NSProgress * _Nonnull progress) {
                
            } callback:^(NSString * _Nonnull path, NSError * _Nonnull error) {
                DISMISS_SVP(0.01);
                //开始OTA升级
                NSString *fileUrl=[[path componentsSeparatedByString:@":///"] lastObject];
                
                NSData *otaBinData = [NSData dataWithContentsOfFile:fileUrl];
                //蓝牙11.30  重点 网络传输 writeOneAndOneDevice 要进入这个方法修改data
//                [FRQBluetoothManager shareManager].fileData = otaBinData
//                [[FRQBluetoothManager shareManager] writeOneAndOneDevice];
                [APP startTimer];
                [[FRQBluetoothManager shareManager] writeOneAndOneDevice:fileUrl];
            }];
        }else{
            [SkToast SkToastShow:model.msg];
        }
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"Cropped Image";
    [self croppedImageView];
    [FRQBluetoothManager shareManager].delegate = self;
    [FRQBluetoothManager shareManager].imgDelegate = self;

}
- (void)fRQCroppedAction{
    _croppedImageView.btnShowOnDevice.enabled = YES;
    [MBProgressHUD hideHUDForView:self.view animated:NO];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[FRQBluetoothManager shareManager] cancelScan];
    //蓝牙12.01
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"FRQCropped" object:nil];
}
- (void)viewWillAppear:(BOOL)animated{
    //蓝牙12.01
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fRQCroppedAction) name:@"FRQCropped" object:nil];
}

//蓝牙11.30
- (void)onImageStartAction{
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    
    MBProgressHUD *progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    progressHUD.label.text = @"Start uploading pictures...";
    progressHUD.mode = MBProgressHUDModeText;
//    [progressHUD hideAnimated:NO afterDelay:0.5];
}

- (void)onImageDidSendAction:(NSInteger)location andLength:(NSInteger)length{
    MBProgressHUD *progressHUD = [MBProgressHUD HUDForView:self.view];
    if (!progressHUD) {
        progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    CGFloat a = location;
    CGFloat b = length;
    double aProgress = a/b * 100;
    progressHUD.label.text = @"The picture is being sent...";
    progressHUD.detailsLabel.text = [NSString stringWithFormat:@"Current progress %.f %%, please wait",aProgress];
    progressHUD.mode = MBProgressHUDModeAnnularDeterminate;
    progressHUD.progress = aProgress/100.0;
    _croppedImageView.btnShowOnDevice.enabled = NO;
}

- (void)onImageFinishAction:(NSInteger)length{
    //蓝牙12.01
    self.croppedImageView.btnShowOnDevice.enabled = YES;
    [MBProgressHUD hideHUDForView:self.view animated:NO];
    //alert
    NSString *alertMsg = @"Picture delivery success";
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"warn" message:alertMsg preferredStyle:UIAlertControllerStyleAlert];
    [alertCtrl addAction:[UIAlertAction actionWithTitle:@"sure" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        FRQDeviceImageViewController *view=[[FRQDeviceImageViewController alloc] init];
        [self.navigationController pushViewController:view animated:YES];
        
    }]];
    
    [self presentViewController:alertCtrl animated:YES completion:^{}];
}
@end
